class Newlist{
    constructor(){
        this.ul = document.querySelector('.list_ul')
        this.span = document.querySelector('span')
        this.init()
    }
    init(){
        this.request()
    }
    request(){
        pAjax({url:'../libs/goods.json'})
        .then(res=>{
            let data = JSON.parse(res)
            data = data.slice(122,189)
            console.log(data)
            this.render(data)
        })
    }
    render(data){
        data.forEach(item => {
            this.ul.innerHTML +=`
            <li>
                    <a href="../html/details.html?id=${item.goods_id}" style="text-decoration:none; color:black;">
                    <div class="pic">
                        <img src="${item.img_small_logo}">
                    </div>
                    <p class="title hide">${item.title}</p>
                    </a>
                    <p class="price">${item.price}</p>
                    <button data-id=${item.goods_id}>加入购物车</button>
                </li>
            ` 
        })
        this.bindHtml(data)
    }
    bindHtml(data){
        this.ul.addEventListener('click',(e)=>{
            let target = e.target
            if(target.nodeName == 'BUTTON'){
                let id = target.dataset.id - 0
                let goods = data.find(item=>{return item.goods_id == id})
                let list = JSON.parse(localStorage.getItem('cart')) || []
                if(list.length){
                    let res = list.some(item=>{return item.goods_id == id})
                    if(res){
                        let index = list.findIndex(item=>{return item.goods_id == id})
                        list[index].cart_number++
                    }else{
                        list.push(goods)
                        goods.cart_number = 1
                    }
                }else{
                    list.push(goods)
                    goods.cart_number = 1
                }
                localStorage.setItem('cart',JSON.stringify(list))
                this.totalNum()
            }
        })
    }
    totalNum(){
        let num = 0
        let list = JSON.parse(localStorage.getItem('cart')) || []
        list.forEach(item=>{
            num += item.cart_number
        })
        this.span.innerHTML = num
    }
}
new Newlist()